import axios from 'axios';

const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000';

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 航班API
export const flightAPI = {
  getAllFlights: (params) => api.get('/flights/', { params }),
  getFlightById: (id) => api.get(`/flights/${id}`),
  createFlight: (data) => api.post('/flights/', data),
  updateFlight: (id, data) => api.put(`/flights/${id}`, data),
  deleteFlight: (id) => api.delete(`/flights/${id}`),
  searchFlights: (params) => api.get('/flights/search', { params }),
};

// 乘客API
export const passengerAPI = {
  getAllPassengers: (params) => api.get('/passengers/', { params }),
  getPassengerById: (id) => api.get(`/passengers/${id}`),
  createPassenger: (data) => api.post('/passengers/', data),
  updatePassenger: (id, data) => api.put(`/passengers/${id}`, data),
  deletePassenger: (id) => api.delete(`/passengers/${id}`),
  searchPassengers: (params) => api.get('/passengers/search', { params }),
};

// 预订API
export const bookingAPI = {
  getAllBookings: (params) => api.get('/bookings/', { params }),
  getBookingByNumber: (bookingNumber) => api.get(`/bookings/${bookingNumber}`),
  createBooking: (data) => api.post('/bookings/', data),
  updateBooking: (id, data) => api.put(`/bookings/${id}`, data),
  deleteBooking: (id) => api.delete(`/bookings/${id}`),
  getPassengerBookings: (passengerId) => api.get(`/bookings/passenger/${passengerId}`),
  cancelBooking: (bookingNumber) => api.put(`/bookings/${bookingNumber}/cancel`),
  updateBookingSeat: (bookingNumber, seatData) => api.put(`/bookings/${bookingNumber}/seat`, seatData),
  getAvailableSeats: (flightId) => api.get(`/bookings/flight/${flightId}/seats`),
  getBookingStats: () => api.get('/bookings/stats/overview'),
  searchBookings: (params) => api.get('/bookings/search', { params }),
};

// 报表API
export const reportAPI = {
  getFlightLoadRate: (params) => api.get('/reports/flight-load-rate', { params }),
  getRevenueStats: (params) => api.get('/reports/revenue', { params }),
  getPassengerStats: (params) => api.get('/reports/passenger-stats', { params }),
  getBookingStats: (params) => api.get('/reports/booking-stats', { params }),
};

export default api;